const mongoose = require("../common/db");
const express = require("express");
// const translateDataToTree = require('../utils/arrayToTree');
const { Schema } = require("mongoose");
const router = express.Router();
let departYearBudgetValueSchema = new mongoose.Schema({
  depart:{
    type:Schema.Types.ObjectId,
    ref:'departModel'
  },
  year: String,
budgetCourse:{
    type:Schema.Types.ObjectId,
    ref:'budgetCourseModel'
},
  budgetCourseValue:String
});
const departModel = mongoose.model("departModel");
const departYearBudgetValueModel =  mongoose.model("departYearBudgetValueModel", departYearBudgetValueSchema);
const yearBudgetModel = mongoose.model("yearBudgetModel");
const budgetCourseModel = mongoose.model("budgetCourseModel");
// 创建
router.post("/", async (req, res, next) => {
  try {
    const ret = await departYearBudgetValueModel.insertMany(req.body)
    res.status(200).json({
      data: ret,
    });
  } catch (err) {
    next(err);
  }
});
// 获取Table列表
router.get('/all',async(req,res,next)=>{
  try {
    const allDepartYearBudget = await departYearBudgetValueModel.find().populate('depart','name')
    res.status(200).json(allDepartYearBudget)
  } catch (err) {
    next(err)
  }
})
//获取所有数据
router.get("/", async (req, res, next) => {
  try {
    let queryData = {}
     Object.keys(req.query).forEach((k)=>{if (req.query[k]!=='' && req.query!== null) {
      queryData[k] = req.query[k]
    }})
   const result = await departYearBudgetValueModel.find(queryData).populate('depart').populate('budgetCourse')
    res.status(200).json(result);
  } catch (err) {
    next(err);  }
});
// 更新
router.patch('/:id',async (req,res,next)=>{
  try {
    const findAndUpdateYearBudget = await departYearBudgetValueModel.findOneAndUpdate({_id:req.body.id},{$set:{
      targetKeysList:req.body.targetKeysList
    }})
    res.status(200).json(findAndUpdateYearBudget)
  } catch (err) {
    next(err)
  }
})

// 删除部门 --- 自己测试用
router.delete('/',async (req,res,next)=>{
  try {
  const ret = await departYearBudgetValueModel.deleteMany(req.body)
  res.status(200).json({
    data:ret
  })
  } catch (err) {
    next(err)
  }
})
// 根据年份和部门获取当年该部门的预算科目
router.get('/detail',async (req,res,next)=>{
  try {
   const ret = await departYearBudgetValueModel.findOne(req.query).populate('targetKeysList')
   res.status(200).json(ret)
  } catch (err) {
    next(err)
  }
})

module.exports = router;
